<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind" label-width="120px">
      <uni-forms-item name="user_id" label="活动发起者的ID" required>
        <uni-easyinput placeholder="活动的发起者的ID， 参考`uni-id-users` 表" :disabled="true" v-model="userId"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="category_id" label="分类" required>
        <uni-data-picker v-model="formData.category_id" collection="opendb-news-categories"
          field="name as text, _id as value"></uni-data-picker>
      </uni-forms-item>
      <uni-forms-item name="title" label="活动名称" required>
        <uni-easyinput placeholder="活动的标题名称" v-model="formData.title" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="avatar" label="活动简介大图" required>
        <uni-file-picker v-model="formData.avatar" fileMediatype="image" return-type="object"
          :auto-upload="true"></uni-file-picker>
      </uni-forms-item>
      <uni-forms-item name="content" label="活动详情大图" required>
        <uni-file-picker v-model="formData.content" fileMediatype="image" return-type="object"
          :auto-upload="true"></uni-file-picker>
      </uni-forms-item>
      <uni-forms-item name="article_status" label="活动状态">
        <uni-data-checkbox v-model="formData.article_status"
          :localdata="formOptions.article_status_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="start_time" label="开始时间" required>
        <uni-datetime-picker return-type="timestamp" v-model="formData.start_time"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="end_time" label="结束时间" required>
        <uni-datetime-picker return-type="timestamp" v-model="formData.end_time"></uni-datetime-picker>
      </uni-forms-item>

      <!-- 新增地区选择器 -->
      <w-three-picker ref="pickerRegionAddress" :title="['省', '市', '区']" :localdata="provinces" v-model="valueAddress"
        @confirm="confirmAddress" :is-mask-click="false" :show-cancel="true" text-field="name" value-field="code" />
      <uni-forms-item name="address" label="活动的省/市/区" required>
        <uni-easyinput @focus="handleFocusRegionAddress" placeholder="省/市/区" v-model="formData.address"
          trim="both"></uni-easyinput>
      </uni-forms-item>

      <uni-forms-item name="location_name" label="活动地点名称" required>
        <uni-easyinput placeholder="活动举办地点名称" v-model="formData.location_name" trim="both"></uni-easyinput>
      </uni-forms-item>

      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;" @click="goBack">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
import { validator } from '@/js_sdk/validator/news-articles-image.js';
import { store } from '@/uni_modules/uni-id-pages/common/store'

const db = uniCloud.database();
const dbCmd = db.command;
const dbCollectionName = 'news-articles-image';

function getValidator(fields) {
  let result = {}
  for (let key in validator) {
    if (fields.includes(key)) {
      result[key] = validator[key]
    }
  }
  return result
}

export default {
  data() {
    let formData = {
      "user_id": "",
      "category_id": "",
      "avatar": "",
      "content": "",
      "article_status": 0,
      "last_comment_user_id": "",
      "publish_date": null,
      "last_modify_date": null,
      "title": "",
      "coupon_id": "",
      "start_time": null,
      "end_time": null,
      "regionAddress": "", // 新增的字段 "address": "province/city/district",
      "location_name": "",
      "view_count": null,
      "like_count": null,
      "location_ip": ""
    }
    return {
      provinces: [], // 初始化为空数组
      valueAddress: ['', '', ''],
      formData,
      formOptions: {
        "article_status_localdata": [
          {
            "value": 0,
            "text": "草稿箱"
          },
          {
            "value": 1,
            "text": "已发布"
          },
          {
            "value": 2,
            "text": "已过期"
          }
        ]
      },
      rules: {
        ...getValidator(Object.keys(formData))
      }
    }
  },
  computed: {
    userId() {
      if (store.hasLogin) {
        this.formData.user_id = store.userInfo._id
        return store.userInfo._id
      }
      uni.showModal({
        content: '获取用户信息失败，请重新登录',
        showCancel: false
      })
      return ''
    }
  },
  onReady() {
    this.$refs.form.setRules(this.rules)
  },
  onLoad() {
    // this.loadRegionData();
    this.getGuangxiRegionData();
  },
  methods: {
    confirmRegionAddress(e) {
      // 将选中的省市区文本拼接并赋值给location_name
      this.formData.regionAddress = e.text.join('/');
    },
    // 加载地区数据
    async loadRegionData() {
      const db = uniCloud.database();
      // 获取省级数据
      const res = await db.collection('opendb-city-china')
        .where({
          type: 0 // 0表示省级
        })
        .get();

      this.provinces = res.result.data.map(province => ({
        name: province.name,
        code: province.code,
        children: [] // 先初始化空children
      }));

      // 预加载市级和区级数据
      for (let province of this.provinces) {
        // 加载市级数据
        const cityRes = await db.collection('opendb-city-china')
          .where({
            parent_code: province.code,
            type: 1 // 1表示市级
          })
          .get();

        province.children = cityRes.result.data.map(city => ({
          name: city.name,
          code: city.code,
          children: [] // 初始化空children
        }));

        // 为每个市级加载区级数据
        for (let city of province.children) {
          const districtRes = await db.collection('opendb-city-china')
            .where({
              parent_code: city.code,
              type: 2 // 2表示区级
            })
            .get();

          city.children = districtRes.result.data.map(district => ({
            name: district.name,
            code: district.code,
            children: null // 区级没有下级
          }));
        }
      }
    },
    goBack() {
      const eventChannel = this.getOpenerEventChannel()
      if (eventChannel && eventChannel.emit) {
        eventChannel.emit('refreshData')
      }
      setTimeout(() => uni.navigateBack(), 500)
    },

    /**
     * 验证表单并提交
     */
    submit() {
      uni.showLoading({
        mask: true
      })
      this.$refs.form.validate().then((res) => {
        return this.submitForm(res)
      }).catch(() => {
      }).finally(() => {
        uni.hideLoading()
      })
    },

    /**
     * 提交表单
     */
    submitForm(value) {
      // 处理图片数据格式
      const submitData = { ...value }

      if (submitData.avatar && submitData.avatar.url) {
        submitData.avatar = submitData.avatar.url
      }
      if (submitData.content && submitData.content.url) {
        submitData.content = submitData.content.url
      }

      // 使用 clientDB 提交数据
      return db.collection(dbCollectionName).add(submitData).then((res) => {
        uni.showToast({
          title: '新增成功'
        })
        this.getOpenerEventChannel().emit('refreshData')
        setTimeout(() => uni.navigateBack(), 500)
      }).catch((err) => {
        uni.showModal({
          content: err.message || '请求服务失败',
          showCancel: false
        })
      })
    },

    // 获取广西及其下辖市、区数据
    async getGuangxiRegionData() {
      const db = uniCloud.database();

      // 1. 获取广西省级数据
      const provinceRes = await db.collection('opendb-city-china')
        .where({
          name: '广西壮族自治区',
          type: 0
        })
        .get();

      if (provinceRes.result.data.length === 0) {
        console.error('未找到广西壮族自治区数据');
        return null;
      }

      const guangxi = provinceRes.result.data[0];

      // 2. 获取广西下辖市级数据
      const citiesRes = await db.collection('opendb-city-china')
        .where({
          parent_code: guangxi.code,
          type: 1
        })
        .get();

      guangxi.children = citiesRes.result.data;

      // 3. 获取每个市下辖的区级数据
      for (const city of guangxi.children) {
        const districtsRes = await db.collection('opendb-city-china')
          .where({
            parent_code: city.code,
            type: 2
          })
          .get();

        city.children = districtsRes.result.data;
      }

      console.log('广西完整地区数据:', guangxi);
      // return guangxi;
      this.provinces = [guangxi];
    },
  },
  handleFocusRegionAddress() {
    // console.log('onFocusAddress');
    this.$refs.pickerRegionAddress.show()
  },
  goBack() {
    const eventChannel = this.getOpenerEventChannel()
    if (eventChannel && eventChannel.emit) {
      eventChannel.emit('refreshData')
    }
    setTimeout(() => uni.navigateBack(), 500)
  },

  /**
   * 验证表单并提交
   */
  submit() {
    uni.showLoading({
      mask: true
    })
    this.$refs.form.validate().then((res) => {
      return this.submitForm(res)
    }).catch(() => {
    }).finally(() => {
      uni.hideLoading()
    })
  },

  /**
   * 提交表单
   */
  submitForm(value) {
    // 处理图片数据格式
    const submitData = { ...value }

    if (submitData.avatar && submitData.avatar.url) {
      submitData.avatar = submitData.avatar.url
    }
    if (submitData.content && submitData.content.url) {
      submitData.content = submitData.content.url
    }

    // 使用 clientDB 提交数据
    return db.collection(dbCollectionName).add(submitData).then((res) => {
      uni.showToast({
        title: '新增成功'
      })
      this.getOpenerEventChannel().emit('refreshData')
      setTimeout(() => uni.navigateBack(), 500)
    }).catch((err) => {
      uni.showModal({
        content: err.message || '请求服务失败',
        showCancel: false
      })
    })
  }
}
</script>
